package kr.hkit.androidcomplete02.ch19;

import kr.hkit.androidcomplete02.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class LooperEx extends Activity {
	int mainValue = 0;
	TextView mainTv;
	TextView backTv;
	EditText numEdit;
	CalcThread mThread;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch19_looper);
		mainTv = (TextView) findViewById(R.id.ch19_looper_mainvalue_tv);
		backTv = (TextView) findViewById(R.id.ch19_looper_backvalue_tv);
		numEdit = (EditText) findViewById(R.id.ch19_looper_number);
		
		mThread = new CalcThread(mHandler);
		mThread.setDaemon(true);
		mThread.start();
	
	}
	
	public void mOnClick(View v){
		Message msg;
		switch(v.getId()){
		case R.id.ch19_looper_increase_btn:
			mainValue++;
			mainTv.setText("MainValue : " + mainValue);
			break;
		case R.id.ch19_looper_square:
			msg = new Message();
			msg.what = 0;
			msg.arg1 = Integer.parseInt(numEdit.getText().toString());
			mThread.mBackHandler.sendMessage(msg);
			break;
		case R.id.ch19_looper_root:
			msg = new Message();
			msg.what = 1;
			msg.arg1 = Integer.parseInt(numEdit.getText().toString());
			mThread.mBackHandler.sendMessage(msg);
			break;
		}
	}
	
	Handler mHandler = new Handler(){
		public void handleMessage(Message msg){
			switch(msg.what){
			case 0:
				backTv.setText("Sqare Result : " + msg.arg1);
				break;
			case 1:
				backTv.setText("Root Result : " + ((Double)msg.obj).doubleValue());
				break;
			}
		}
	};
}

class CalcThread extends Thread{
	Handler mMainHandler;
	Handler mBackHandler;
	
	public CalcThread(Handler mMainHandler) {
		super();
		this.mMainHandler = mMainHandler;
	}
	
	@Override
	public void run() {
		Looper.prepare();
		mBackHandler = new Handler(){
			public void handleMessage(Message msg){
				Message retmsg = new Message();
				switch(msg.what){
				case 0:
					try{Thread.sleep(200);} catch(InterruptedException e){}
					retmsg.what = 0;
					retmsg.arg1 = msg.arg1 * msg.arg1;
					break;
				case 1:
					try{Thread.sleep(200);} catch(InterruptedException e){}
					retmsg.what = 1;
					retmsg.obj = new Double(Math.sqrt((double)msg.arg1));
					break;
				}
				mMainHandler.sendMessage(retmsg);
			}
		};
		Looper.loop();
	}
	
}